package com.sdkj.dspservice.common.exceptions;

import com.sdkj.dspservice.common.react.AntdProResult;
import com.sdkj.dspservice.common.base.entity.BaseResult;
import com.sdkj.dspservice.common.utils.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 全局异常处理
 *
 * @author tm
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 后台参数校验
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResult validationErrorHandler(MethodArgumentNotValidException ex, HttpServletResponse response) {
        AntdProResult result = new AntdProResult();
        // 获取错误
        BindingResult bindingResult = ex.getBindingResult();
        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
        // 组装错误
        StringBuffer stringBuilder = new StringBuffer("数据验证失败：");
        for (FieldError fieldError : fieldErrorList) {
            stringBuilder.append(fieldError.getDefaultMessage() + ",");
        }
        // 去掉末尾的逗号
        result.error(AntdProResult.VALIDATOR_ERROR, StringUtils.removeEnd(stringBuilder.toString(), 1));
        return result;
    }
}
